package com.heima.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.vo.LoginVo;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.sun.corba.se.spi.ior.ObjectKey;
import org.junit.Assert;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {

        String phone = dto.getPhone();
        String password = dto.getPassword();
        Map<String, Object> resultMap = new HashMap<>();
        if (phone.isEmpty() && password.isEmpty()){
            String token = AppJwtUtil.getToken(0L);
            resultMap.put("token",token);
            return ResponseResult.okResult(resultMap);
        }
        // 查询数据库
        ApUser user = lambdaQuery().eq(ApUser::getPhone, phone).one();
        if (Objects.isNull(user)){
            throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        // 检查账号状态
        if (user.getStatus()){
           throw new CustomException(AppHttpCodeEnum.INVALID_STATUS);
        }
        // 校验密码
        if(!BCrypt.checkpw(password,user.getPassword())){
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 生成token
        String token = AppJwtUtil.getToken(user.getId().longValue());
        LoginVo vo = new LoginVo(user.getId(),user.getName(),user.getPhone());
        resultMap.put("user",vo);
        resultMap.put("token",token);

        return ResponseResult.okResult(resultMap);
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
